<template>
  <div class="page-main" v-title data-title="技术/经验库">
    <FixedMenu menuClass="fixed-menu">
      <div class="fixed-menu">
        <div class="functionMould" style="background-color: #ffffff" @click="handleMyFile(1)">
          <a-icon type="history" class="menu-icon" />
          <span> 历史版本</span>
        </div>
        <div class="functionMould" style="background-color: #ffffff" @click="handleMyFile(2)">
          <a-icon type="file-text" class="menu-icon" />
          <span> 文件评价</span>
        </div>
        <div class="functionMould" style="background-color: #ffffff" @click="handleMyFile(3)">
          <a-icon type="lock" class="menu-icon" />
          <span>变更详情</span>
        </div>
      </div>
    </FixedMenu>
    <home-nav :userData="userinfo"></home-nav>
    <div class="container" ref="imageWrapper">
      <div class="head-content">
        <span class="bold-font">工程技术/经验库</span>
        <div class="btn-line">
          <div v-if="isHistory" style="color: red">当前为历史版本[{{ form.publishVersion }}] 不允许改版</div>
          <a-button
            v-if="!isHistory && (!!editAble || !!reEditAble || checkCurrentTask(['submit']))"
            @click="handleSave('save')"
            class="hte-btn add-btn"
            type="primary"
          >
            保存
          </a-button>
          <a-button
            v-if="!isHistory && [2, 5].indexOf(form.status) > -1"
            @click="handleQuote('quote')"
            class="hte-btn add-btn"
          >
            引用申请
          </a-button>
          <a-button
            v-if="!isHistory && (!!editAble || checkCurrentTask(['submit']))"
            @click="handleSubmit('submit')"
            class="hte-btn add-btn"
          >
            提交
          </a-button>
          <a-button v-if="!isHistory && [0, 3].indexOf(form.status) > -1" @click="handleDele()" style="color: red">
            删除
          </a-button>

          <a-button
            v-if="!isHistory && [2].indexOf(form.status) > -1"
            @click="handleSave('reEdit')"
            class="hte-btn add-btn"
          >
            改版
          </a-button>
          <a-button v-if="!isHistory && !!reEditAble" @click="handleSave('rePublish')" class="hte-btn add-btn">
            改版发布
          </a-button>
          <a-button v-if="!isHistory && !!reEditAble" @click="handleSave('cancelReEdit')" class="hte-btn add-btn">
            取消改版
          </a-button>
        </div>
      </div>
      <div class="content">
        <a-form-model ref="ruleForm" :rules="rules" :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
          <section>
            <div class="section-header">
              <div style="float: left">
                基本信息
                <div class="mouldTips">
                  <img src="@/assets/icon_warning2.png" style="display: inline-block; margin-top: -3px" />
                  注意：工程技术/经验库关键参数提交后不可修改，请谨慎操作
                </div>
              </div>
              <div style="float: right; margin-right: 20px">
                <!-- <a-button type="link" style="color: red" @click="showEngineeFlowTips">流程审批说明</a-button> -->
              </div>
            </div>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="项目号编">
                  <div
                    style="display: flex; justify-content: start; align-items: center; line-height: 40px; height: 40px"
                  >
                    <a-select
                      style="width: 30%"
                      v-model="form.hasProjectNo"
                      :disabled="isHistory || (!editAble && !reEditAble)"
                      @change="chagneHasProjectNo"
                    >
                      <a-select-option v-for="d in codes['是否']" :value="d.code" :key="d.code"
                        >{{ d.name }}
                      </a-select-option>
                    </a-select>
                    <a-input-search
                      readOnly
                      :disabled="isHistory || (!editAble && !reEditAble) || form.hasProjectNo != '1'"
                      :placeholder="form.hasProjectNo != '1' ? '' : '选择项目编号'"
                      v-model="form.projectNo"
                      @search="openProjectSelector"
                    />
                  </div>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目经理：" ref="projectManager">
                  <UserInputSelector
                    :username.sync="form.projectManagerId"
                    :realname.sync="form.projectManager"
                    multiple="multiple"
                    placeholder="请选择"
                    :disabled="isHistory || (!editAble && !reEditAble) || form.hasProjectNo != '1'"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目名称：" ref="projectName">
                  <a-input
                    v-model="form.projectName"
                    :disabled="isHistory || (!editAble && !reEditAble) || form.hasProjectNo != '1'"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="技术/经验编号：">
                  <a-input disabled :value="form.techNo" />
                </a-form-model-item>
              </a-col>
              <a-col :span="16">
                <a-form-model-item label="技术/经验名称：" ref="name" prop="techName">
                  <a-input v-model="form.techName" :disabled="isHistory || (!editAble && !reEditAble)" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="技术/经验等级：" ref="techLevel" prop="techLevel">
                  <div
                    style="display: flex; justify-content: start; align-items: center; line-height: 40px; height: 40px"
                  >
                    <a-select v-model="form.techLevel" :disabled="isHistory || (!editAble && !reEditAble)">
                      <a-select-option v-for="d in codes['工程技术库-技术等级']" :value="d.code" :key="d.code"
                        >{{ d.name }}
                      </a-select-option>
                    </a-select>
                    <!-- <a-button type="link" @click="openTechDegreeTest">测评</a-button> -->
                  </div>
                </a-form-model-item>
              </a-col>

              <a-col :span="8">
                <a-form-model-item label="技术/经验类型" ref="techType" prop="techType">
                  <CodeSelector
                    type="select"
                    :codes="codes['技术库-类型']"
                    codeKey="code"
                    nameKey="name"
                    :code.sync="form.techType"
                    :disabled="!!form.techNo"
                    multiple="default"
                    @change="changeTechType"
                  ></CodeSelector>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="技术/经验类别：" ref="techCategory" prop="techCategory">
                  <a-select
                    default-value="1"
                    style="width: 100%"
                    v-model="form.techCategory"
                    :disabled="isHistory || (!editAble && !reEditAble)"
                  >
                    <a-select-option v-for="d in codes['技术库-技术类别（专业）']" :value="d.code" :key="d.code"
                      >{{ d.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="关键词" prop="keyWord">
                  <a-input
                    v-model="form.keyWord"
                    placeholder="关键词用顿号“、”隔开"
                    :disabled="isHistory || (!editAble && !reEditAble)"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="文件形式：" ref="fileType" prop="fileType">
                  <a-select
                    default-value="1"
                    style="width: 100%"
                    v-model="form.fileType"
                    :disabled="isHistory || (!editAble && !reEditAble)"
                  >
                    <a-select-option v-for="d in codes['技术库-文件形式']" :value="d.code" :key="d.code"
                      >{{ d.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="编制人" ref="compileUser" prop="compileUser">
                  <div
                    style="display: flex; justify-content: start; align-items: center; line-height: 40px; height: 40px"
                  >
                    <UserInputSelector
                      :disabled="isHistory || (!editAble && !reEditAble)"
                      :username.sync="form.compileUserId"
                      :realname.sync="form.compileUser"
                      multiple="default"
                      placeholder="编制人"
                    />
                  </div>
                </a-form-model-item>
              </a-col>
            </a-row>

            <a-row :gutter="24">
              <a-col :span="16">
                <a-form-model-item label="技术/经验简介：" ref="techIntro" prop="techIntro">
                  <a-textarea
                    :auto-size="{ minRows: 1, maxRows: 6 }"
                    v-model="form.techIntro"
                    :maxLength="500"
                    :disabled="isHistory || (!editAble && !reEditAble)"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="参与人" ref="compileUser" prop="compileUser">
                  <div
                    style="display: flex; justify-content: start; align-items: center; line-height: 40px; height: 40px"
                  >
                    <UserInputSelector
                      :disabled="isHistory || (!editAble && !reEditAble)"
                      :username.sync="form.participantsId"
                      :realname.sync="form.participants"
                      multiple="multiple"
                      placeholder="参与人"
                    />
                  </div>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-model-item label="应用场景" ref="techScenario" prop="techScenario">
                  <a-textarea
                    :auto-size="{ minRows: 1, maxRows: 6 }"
                    :maxLength="200"
                    v-model="form.techScenario"
                    :disabled="isHistory || (!editAble && !reEditAble)"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-model-item label="技术/经验优/缺点：" ref="techAdvertage" prop="techAdvertage">
                  <a-textarea
                    :disabled="isHistory || (!editAble && !reEditAble)"
                    placeholder="技术/经验优点:
技术/经验缺点:
注意事项:"
                    :auto-size="{ minRows: 2, maxRows: 6 }"
                    v-model="form.techAdvertage"
                    :maxLength="500"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>

            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="创建人/部门">
                  <a-input
                    :value="
                      (form.createUser ? form.createUser : '') + '/' + (form.createUserDept ? form.createUserDept : '')
                    "
                    disabled
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="创建时间">
                  <a-input :value="form.createTime" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="发布版本时间">
                  <div
                    style="display: flex; justify-content: start; align-items: center; line-height: 40px; height: 40px"
                  >
                    <a-input :value="form.publishTime" disabled />
                    <a-input
                      :value="form.publishVersion == 0 ? '未发布' : 'V' + form.publishVersion"
                      disabled
                      style="width: 80px; text-align: center"
                    />
                  </div>
                </a-form-model-item>
              </a-col>
            </a-row>
          </section>
        </a-form-model>
        <section v-if="form.id">
          <div class="section-header">技术/经验知识产权-专利</div>
          <div class="section-table">
            <div class="table-operations">
              <a-button v-if="editAble || reEditAble" type="primary" @click="patentAdd"> 新增 </a-button>
              <a-button v-if="editAble || reEditAble" @click="patentRemove"> 删除 </a-button>
              <a-table
                class="hte-table-content"
                :columns="patent.columns"
                :data-source="patentList"
                :pagination="false"
                size="middle"
                rowKey="id"
                :row-selection="{ selectedRowKeys: patent.selectedRowKeys, onChange: onPatentSelectChange }"
              >
                <template slot="patentCode" slot-scope="text, record">
                  <a-input
                    v-model="record.code"
                    @change="forceUpdate"
                    :disabled="isHistory || (!editAble && !reEditAble)"
                    placeholder="32字以内"
                    :maxLength="32"
                  />
                </template>
                <template slot="patentName" slot-scope="text, record">
                  <a-input
                    v-model="record.name"
                    @change="forceUpdate"
                    :disabled="isHistory || (!editAble && !reEditAble)"
                    placeholder="32字以内"
                    :maxLength="32"
                  />
                </template>
                <template slot="patentAmount" slot-scope="text, record">
                  <a-input-number
                    v-model="record.amount"
                    @change="forceUpdate"
                    :disabled="isHistory || (!editAble && !reEditAble)"
                    :min="0"
                    :max="1000000"
                  />
                </template>
                <template slot="patentLink" slot-scope="text, record">
                  <a-input
                    v-model="record.link"
                    @change="forceUpdate"
                    :disabled="isHistory || (!editAble && !reEditAble)"
                    placeholder="125字以内"
                    :maxLength="125"
                  />
                </template>
              </a-table>
            </div>
          </div>
        </section>
        <section v-if="form.id">
          <div class="section-header">
            技术/经验文件
            <div class="mouldTips">
              <img src="@/assets/icon_warning2.png" style="display: inline-block; margin-top: -3px" />
              注意：此处上传的附件是技术/经验文件，在海芯可以继续阅读。
            </div>
           
          </div>
          <AttachList
            ref="coreFile"
            :busField="form.techNo + ''"
            busType="techFileCore"
            :busKey="attachBusKey"
            busField="techFileCore"
            :zipFileName="form.techNo + '#' + form.techName"
            :showUpload="!isHistory && (editAble || reEditAble)"
            :showDelete="!isHistory && (editAble || reEditAble)"
            @afterUpload="afterUpload"
            @afterDel="afterDel"
            @afterDown="afterDown"
            :showDown="editAble || reEditAble || canDown"
            :beforeUpload="beforeUpload"
          />
        </section>
        <section v-if="form.id">
          <div class="section-header">其他文件</div>
          <AttachList
            ref="otherFile"
            :busField="form.techNo + ''"
            busType="techFileOthers"
            busField="techFileOthers"
            :busKey="attachBusKey"
            :zipFileName="form.techNo + '#' + form.techName"
            :showUpload="!isHistory && (editAble || reEditAble)"
            :showDelete="!isHistory && (editAble || reEditAble)"
            @afterUpload="afterUpload1"
            @afterDel="afterDel1"
            @afterDown="afterDown"
            :showDown="editAble || reEditAble || canDown"
            :beforeUpload="beforeUpload"
          />
        </section>
        <section v-if="form.id">
          <div class="section-header">技术/经验综合情况</div>
          <div class="section-table">
            <div style="display: flex; justify-content: end">
              <a-button type="primary" @click="toOpenComments">我要评价</a-button>
            </div>
            <div>
              <a-table :columns="colums" :data-source="[form]" :pagination="false" size="middle" rowKey="id">
                <template slot="name" slot-scope="text, record">
                  <a @click="showAttach(record)">{{ record.name }}</a>
                </template>
              </a-table>
            </div>
          </div>
        </section>
        <section v-if="form.processInstanceId">
          <div class="section-header">审核信息</div>
          <ht-approval
            ref="childrenRef"
            :process-instance-id="form.processInstanceId"
            :custom="custom"
            :options="options"
            @submit="afterSubmit"
            @reject="afterReject"
            @back="backAction"
            @cancelSubmit="afterCancelSubmit"
            :before-fill-opinion="saveNotifyOpinion"
            :before-submit="beforeSubmit"
            :before-reject="beforeReject"
            :show-task-history="true"
            :history-dialog="historyDialog"
            :task-load="taskLoad"
            :message-id="messageId"
            :showPrintBtn="showPrintBtn"
            :show-upload-btn="false"
            :hidden-task-def-key="hiddenTaskDefKey"
            :snapshotConfigs="snapshotConfigs"
            :print="print"
          >
          </ht-approval>
        </section>
      </div>
    </div>
    <TechDegreeTest ref="TechDegreeTest" @close="closeTechDegreeTest" />
    <EngineeFlowTips ref="EngineeFlowTips" />
    <projectSelector @close="closeProjectSelector" ref="projectSelector" />
    <ProcessUserSelect ref="ProcessUserSelect" @selectUserConfirm="selectUserConfirm" />
    <Comments ref="Comments" @afterComment="afterComment" />
    <NewTechEngineeHistoryList ref="NewTechEngineeHistoryList" />
    <CommentsListModal ref="CommentsListModal" />
    <LogList ref="LogList" />
  </div>
</template>
<script>
import { strNotNull, getQuery } from '@/utils/common.js'
import { getAction, postAction, previewAttach } from '@/api/manage'
import { ACCESS_TOKEN, USER_INFO } from '@/store/mutation-types'
import { TreeSelect } from 'ant-design-vue'
import { formatFileSize, endWith } from '@/utils/common.js'
import { Modal } from 'ant-design-vue'
import Vue from 'vue'
import '@/config/upload.install.js'
const SHOW_PARENT = TreeSelect.SHOW_PARENT
import { FlowMixin } from '@/mixins/FlowMixin'
import { CodesMixin } from '@/mixins/CodesMixin'
import FixedMenu from '@/components/tools/FixedMenu'
import { postActionAsync } from '../../../api/manage'
export default {
  mixins: [FlowMixin, CodesMixin],
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),
    htApproval: () => import('@/config/ht-approval.umd.min.js'),
    TechDegreeTest: () => import('@/views/tech/techDegree/TechDegreeTest'),
    EngineeFlowTips: () => import('@/views/tech/enginee/EngineeFlowTips'),
    Comments: () => import('@/views/tech/enginee/comments/Comments'),
    projectSelector: () => import('@/views/projectBuild/projectSelector'),
    ProcessUserSelect: () => import('@/components/tools/ProcessUserSelect'),
    AttachList: () => import('@/components/attach/AttachList'),
    NewTechEngineeHistoryList: () => import('@/views/tech/enginee/history/HistoryList'),
    CommentsListModal: () => import('@/views/tech/enginee/comments/CommentsListModal'),
    LogList: () => import('@/views/tech/enginee/logs/LogList'),
    FixedMenu,
  },
  data() {
    return {
      currentUserId: Vue.ls.get(USER_INFO).username,
      SHOW_PARENT,
      messageId: '',
      form: {
        techAdvertage: '技术/经验优点:\n技术/经验缺点:\n注意事项:\n',
        processInstanceId: '',
        hasProjectNo: '1',
        patentList: [],
      },
      patentList: [],
      rules: {
        projectNo: [],

        // projectManager: [
        //   {
        //     required: true,
        //     message: '请选择项目经理',
        //     trigger: 'blur',
        //   },
        // ],
        // projectName: [
        //   {
        //     required: true,
        //     message: '请选择项目名称',
        //     trigger: 'blur',
        //   },
        // ],
        projectName: [
          {
            required: true,
            message: '请输入项目名称',
            trigger: 'blur',
          },
        ],
        // compileUser: [
        //   {
        //     required: true,
        //     message: '请选择编制人',
        //     trigger: 'blur',
        //   },
        // ],
        // participants: [
        //   {
        //     required: true,
        //     message: '请选择参与人',
        //     trigger: 'blur',
        //   },
        // ],
        techName: [
          {
            required: true,
            message: '请输入技术/经验名称',
            trigger: 'blur',
          },
        ],
        techLevel: [
          {
            required: true,
            message: '请选择技术/经验等级',
            trigger: 'blur',
          },
        ],
        techType: [
          {
            required: true,
            message: '请选择技术/经验类型',
            trigger: 'blur',
          },
        ],
        keyWord: [
          {
            required: true,
            message: '请输入关键词',
            trigger: 'blur',
          },
        ],
        techScenario: [
          {
            required: true,
            message: '请输入应用场景',
            trigger: 'blur',
          },
          { min: 1, max: 500, message: '技术/经验应用场景不超过500个字', trigger: 'blur' },
        ],
        techIntro: [
          {
            required: true,
            message: '请输入技术/经验简介',
            trigger: 'blur',
          },
          { min: 1, max: 500, message: '技术/经验简介不超过500个字', trigger: 'blur' },
        ],

        techAdvertage: [
          {
            required: true,
            message: '请输入技术/经验优/缺点',
            trigger: 'blur',
          },
          { min: 1, max: 500, message: '技术/经验缺陷不超过500个字', trigger: 'blur' },
        ],
        projectManager: [
          {
            required: true,
            message: '请输入项目经理',
            trigger: 'blur',
          },
        ],
        fileType: [
          {
            required: true,
            message: '请选择文件形式',
            trigger: 'blur',
          },
        ],
        techCategory: [
          {
            required: true,
            message: '请选择技术/经验类别',
            trigger: 'blur',
          },
        ],
      },
      dicts: {
        flagDict: [
          { code: 1, name: '是' },
          { code: 0, name: '否' },
        ],
      },
      techKeyWordTree: [],
      fileTypeDic: [],
      techCategoryDic: [],
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'ContractReportInfo',
      },
      labelCol: { span: 8 },
      wrapperCol: { span: 15 },

      patent: {
        columns: [
          {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            align: 'center',
            width: 10,
            customRender: (text, record, index) => `${index + 1}`,
          },
          {
            title: '专利号',
            width: 100,
            scopedSlots: { customRender: 'patentCode' },
          },
          {
            title: '名称',
            width: 150,
            scopedSlots: { customRender: 'patentName' },
          },
          {
            title: '数量',
            width: 50,
            scopedSlots: { customRender: 'patentAmount' },
          },
          {
            title: '专利链接',
            width: 300,
            scopedSlots: { customRender: 'patentLink' },
          },
        ],
        currentSelection: [],
        selectedRowKeys: [],
        freshKey: 0,
      },
      colums: [
        {
          title: '查阅次数',
          dataIndex: 'viewTimes',
          key: 'viewTimes',
          align: 'center',
        },
        {
          title: '引用次数',
          dataIndex: 'quoteTimes',
          key: 'quoteTimes',
          align: 'center',
        },
        {
          title: '下载次数',
          dataIndex: 'downTimes',
          key: 'downTimes',
          align: 'center',
        },
        {
          title: '评价次数',
          dataIndex: 'commentsTimes',
          key: 'commentsTimes',
          align: 'center',
        },
        {
          title: '综合评分',
          dataIndex: 'commonScore',
          key: 'commonScore',
          align: 'center',
        },
        {
          title: '专利数量',
          dataIndex: 'patendNums',
          key: 'patendNums',
          align: 'center',
        },
      ],
      urls: {
        save: '/hteEngineeTechLib/edit',
        info: '/hteEngineeTechLib/info',
        getAttachs: '/tp/attach/getAttaches',
        generateUuid: '/common/generateUuid',
        flowNode: '/hteEngineeTechLib/flowNode',
        startFlow: '/hteEngineeTechLib/startFlow',
        patentList: '/com.haday.hte.rad/techProperty/listByTechId',
        logAdd: 'hteEngineeTechLibLogs/edit',
        addDownTimes: '/hteEngineeTechLib/addDownTimes',
        checkDownPower: '/hteEngineeTechLib/checkDownPower',
        delete: '/hteEngineeTechLib/delete',
        autoPublish: '/hteEngineeTechLib/autoPublish',
      },
      pushUserOriginTargetKeys: [],
      hasConfirmTechDegreeTest: false,
      upmsPermissions: [],
      canDown: false,
    }
  },
  computed: {
    editAble() {
      if (
        !this.form ||
        !this.form.status ||
        [0, 3].indexOf(this.form.status) > -1 ||
        this.currentTask.taskDefKey == 'submit'
      ) {
        return true
      }
      return false
    },
    reEditAble() {
      if ([5].indexOf(this.form.status) > -1 && this.form.reEditUserId == this.currentUserId) {
        return true
      }
      return false
    },
    attachBusKey() {
      if (this.form.id && (this.form.draftVersion || this.form.draftVersion == 0)) {
        if (this.form.id && endWith(this.form.id, '_' + this.form.publishVersion)) {
          return this.form.id
        }
        return this.form.id + '_' + this.form.draftVersion
      }
      return ''
    },
    isHistory() {
      if (this.form.id && endWith(this.form.id, '_' + this.form.publishVersion)) {
        return true
      }
      return false
    },
  },
  mounted() {
    this.fetchCodes([
      '工程技术库状态',
      '工程技术库-技术类型',
      '技术库-技术类别（专业）',
      '技术库-文件形式',
      '工程技术关键字对应等级',
      '技术库-类型',
      '是否',
      '工程技术库-技术等级',
    ])
    this.form.id = getQuery('id', this)
    this.form.code = getQuery('projectNo', this)
    this.messageId = getQuery('messageId', this)
    this.initData()
    this.checkDownPower()
  },
  methods: {
    async initData() {
      await this.fetchInfo()
      await this.fetchPatenList()
    },
    async fetchInfo() {
      if (strNotNull(this.form.id)) {
        let res = await getAction(this.urls.info, { id: this.form.id })
        if (res.success) {
          this.form = res.result
          this.form.isNew = 0

          this.patentList = []
          if (this.form.hasProjectNo) {
            this.form.hasProjectNo = this.form.hasProjectNo + ''
          }
        } else {
          this.$message.warning('加载信息失败，请刷新页面:', res.message)
        }
      } else {
        let res = await getAction(this.urls.generateUuid, {})
        if (res.success) {
          this.form.id = res.result
          this.form.isNew = 1
          this.form.draftVersion = 1
          this.form.publishVersion = 0
          this.patentList = []
        } else {
          this.$message.warning('获取数据id失败，请刷新页面:', res.message)
        }
      }
    },
    async fetchPatenList() {
      if (strNotNull(this.form.id)) {
        let res = await getAction(this.urls.patentList, { techId: this.form.id + '_' + this.form.draftVersion })
        if (res.success) {
          this.patentList = res.result
        } else {
          this.patentList = []
          this.$message.warning('获取专利数据失败，请刷新页面:', res.message)
        }
      }
    },
    handleSave(type) {
      return new Promise(async (resolve, reject) => {
        this.form.techClass = '40'
        this.form.busType = type
        if (this.form.hasProjectNo == '1') {
          if (!this.form.projectNo) {
            this.$message.warning('请输入项目号')
            resolve(false)
            return
          }
        }
        if (!this.form.techType) {
          this.$message.warning('请选择技术/经验类型')
          resolve(false)
          return
        }
        if (this.patentList != null && this.patentList.length > 0) {
          for (var i = 0; i < this.patentList.length; i++) {
            if (this.patentList[i].name.trim() == '') {
              this.$message.warning('【技术知识产权-专利】第' + (i + 1) + '行名称不可为空')
              resolve(false)
              return
            }
          }
        }
        this.form.saveType = type
        this.form.patentList = this.patentList
        let res = await postAction(this.urls.save, this.form)
        if (res.success) {
          this.$message.success('操作成功', 1)
          if (this.form.isNew == 0) {
            this.initData()
          } else {
            this.$router.push('/engineeTech/edit?id=' + res.result.id)
          }
          resolve(true)
          return
        } else {
          this.$message.warning('操作数据出错:' + res.message)
          resolve(false)
          return
        }
      })
    },
    async handleSubmit() {
      let valid = await this.$refs.ruleForm.validate()
      if (valid) {
        // let otherFileList = this.$refs.otherFile.getAttachs()
        // if (otherFileList == null || otherFileList.length <= 0) {
        //   this.$message.warning('请上传《技术等级测评表》附件后再提交！')
        //   return
        // } else {
        //   let hasFile = false
        //   otherFileList.forEach((f) => {
        //     if (f.fileName.indexOf('技术等级测评表') > -1) {
        //       hasFile = true
        //     }
        //   })
        //   if (!hasFile) {
        //     this.$message.warning('请上传《技术等级测评表》附件后再提交！')
        //     return
        //   }
        // }
        await this.handleSave()
        let that = this
        if (this.form.techLevel == '5') {
          Modal.confirm({
            title: '技术等级提交提醒',
            content: '项目等级为其他时，将不会发起审批流程，点击【确认】将自动发布，取消则不发布',
            okText: '确认',
            okType: 'success',
            cancelText: '取消',
            onOk() {
              getAction(that.urls.autoPublish + '?id=' + that.form.id).then((res) => {
                if (res.success) {
                  that.$message.success('提交审批成功')
                  that.initData()
                } else {
                  that.$message.error('提交审批失败:' + res.message)
                }
              })
            },
            onCancel() {},
          })
          return
        }
        this.openUserSelector()
      }
    },
    openUserSelector() {
      getAction(this.urls.flowNode + '?id=' + this.form.id).then((res) => {
        if (res.success) {
          this.$refs.ProcessUserSelect.doSelect(res.result, '')
        } else {
          this.$message.error('获取流程节点信息失败:' + res.message)
        }
      })
    },
    selectUserConfirm(cols) {
      if (this.currentTask.taskDefKey == 'submit') {
        cols.forEach((c) => {
          if (c.value && c.value != null) {
            this.$set(this.custom, c.node, c.value)
          } else {
            this.$set(this.custom, c.node, '')
          }
        })
        this.$refs.childrenRef.custom = this.custom
        this.$refs.childrenRef.submitTaskNotBefore()
        return
      }
      if (cols && cols.length > 0) {
        postAction(this.urls.startFlow + '?id=' + this.form.id, cols).then((res) => {
          if (res.success) {
            this.$message.success('提交审批成功')
            this.initData()
          } else {
            this.$message.error('提交审批失败:' + res.message)
          }
        })
      }
    },
    onPatentSelectChange(selectedRowKeys, selectedRows) {
      this.patent.selectedRowKeys = selectedRowKeys
      this.patent.currentSelection = selectedRows
    },
    patentAdd() {
      let patentList = this.patentList || []
      patentList.push({
        id: Date.now() + this.patentList.length,
        code: '',
        name: '',
        amount: 0,
        link: '',
      })
      this.patentList = patentList
      this.$forceUpdate()
    },
    forceUpdate() {
      this.$forceUpdate()
    },
    patentRemove() {
      if (this.patent.selectedRowKeys.length == 0) {
        this.$message.warning('请选择要删除的技术知识产权-专利')
        return
      }
      var vm = this
      Modal.confirm({
        title: '警告',
        content: '真的要删除吗?,确认后再点击保存删除生效',
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          // 在这里调用删除接口
          for (var i = 0; i < vm.patent.selectedRowKeys.length; i++) {
            for (var j = vm.patentList.length - 1; j >= 0; j--) {
              if (vm.patentList[j].id == vm.patent.selectedRowKeys[i]) {
                vm.patentList.splice(j, 1)
                break
              }
            }
          }
          vm.patent.selectedRowKeys = []
          vm.patent.currentSelection = []
          vm.patent.freshKey++
        },
        onCancel() {
          console.log('patentRemove Cancel')
        },
      })
    },
    changeTechType() {
      let hasTechType = false
      let code = ''
      this.codes['工程技术关键字对应等级'].forEach((d) => {
        // this.form.techTypeArr.forEach((k) => {
        if (this.form.techType != null && this.form.techType.indexOf(d.name) > -1) {
          code = d.code
          hasTechType = true
        }
        // })
      })
      if (hasTechType) {
        this.$set(this.form, 'techLevel', this.codes['工程技术库-技术等级'][parseInt(code) - 1].name)
      }
    },
    openTechDegreeTest() {
      this.$refs.TechDegreeTest.init()
    },
    closeTechDegreeTest() {
      this.hasConfirmTechDegreeTest = true
    },
    checkPermission(permissions) {
      let flag = false
      if (permissions && this.upmsPermissions) {
        permissions.forEach((c) => {
          if (this.upmsPermissions.indexOf(c) >= 0) {
            flag = true
          }
        })
      }
      return flag
    },
    showEngineeFlowTips() {
      this.$refs.EngineeFlowTips.open()
    },
    openProjectSelector() {
      this.$refs.projectSelector.openInit({ projectClasses: ['40', '41'], withOutProjectSubTypes: ['S'] })
    },
    closeProjectSelector(project) {
      if (project) {
        this.$set(this.form, 'projectNo', project.projectNo)
        this.$set(this.form, 'projectName', project.projectName)
        this.$set(this.form, 'projectManager', project.projectManager)
        this.$set(this.form, 'projectManagerId', project.projectManagerId)
      }
    },
    handleDele() {
      let that = this
      if ([1, 2].indexOf(this.form.status) > -1) {
        this.$message.warning('审批中的或审批完成[已发布]的不允许删除')
        return
      }
      Modal.confirm({
        title: '确认删除',
        content: '此操作将删除当前技术库?',
        onOk: function () {
          postAction(that.urls.delete + '?id=' + that.form.id).then((res) => {
            if (res.success) {
              that.$message.success('操作成功')
              window.close()
            } else {
              that.$message.warning('操作失败:', res.message)
            }
          })
        },
      })
    },
    beforeSubmit(res) {
      if (this.currentTask.taskDefKey == 'submit') {
        this.handleSubmit()
        return false
      }
      return true
    },

    beforeUpload() {
      if (!this.form.techNo) {
        this.$message.warning('请先保存基本信息后再上传')
        return false
      } else {
        return true
      }
    },
    afterUpload(response, file, fileList) {
      let fileNames = []
      let ids = []
      response.forEach((r) => {
        fileNames.push(r.fileName)
        ids.push(r.id)
      })
      let log = {}
      log.techId = this.form.id
      log.context = '核心附件-上传文件-' + fileNames.join(',')
      log.type = 'techFileCore'
      log.remark = ids.join(',')
      this.$emit('afterUpload', response, file, fileList)
    },
    afterDel(records) {
      let fileNames = []
      let ids = []
      records.forEach((r) => {
        fileNames.push(r.fileName)
        ids.push(r.id)
      })
      let log = {}
      log.techId = this.form.id
      log.context = '核心附件-删除文件-' + fileNames.join(',')
      log.type = 'techFileCore'
      log.remark = ids.join(',')
      postAction(this.urls.logAdd, log).then((res) => {
        // this.fetchInfo()
      })
    },
    afterUpload1(response, file, fileList) {
      let fileNames = []
      let ids = []
      response.forEach((r) => {
        fileNames.push(r.fileName)
        ids.push(r.id)
      })
      let log = {}
      log.techId = this.form.id
      log.context = '其他附件-上传文件-' + fileNames.join(',')
      log.type = 'techFileOthers'
      log.remark = ids.join(',')
      postAction(this.urls.logAdd, log).then((res) => {
        // this.fetchInfo()
      })
    },
    afterDel1(records) {
      let fileNames = []
      let ids = []
      records.forEach((r) => {
        fileNames.push(r.fileName)
        ids.push(r.id)
      })
      let log = {}
      log.techId = this.form.id
      log.context = '其他附件-删除文件-' + fileNames.join(',')
      log.type = 'techFileOthers'
      log.remark = ids.join(',')
      postAction(this.urls.logAdd, log).then((res) => {
        // this.fetchInfo()
      })
    },
    afterDown(List) {
      this.form.downTimes = this.form.downTimes + List.length
      getAction(this.urls.addDownTimes + '?id=' + this.form.id + '&addDownTimes=' + List.length).then((res) => {
        this.fetchInfo()
      })
    },
    toOpenComments() {
      this.$refs.Comments.open(this.form.id)
    },
    afterComment() {
      this.fetchInfo()
    },
    checkDownPower() {
      getAction(this.urls.checkDownPower + '?id=' + this.form.id).then((res) => {
        if (res.success) {
          this.canDown = res.result
        }
      })
    },
    handleQuote() {
      let urlJump = this.$router.resolve({ path: `/engineeTech/quote?techId=` + this.form.id })
      window.open(urlJump.href, '_blank')
    },
    handleMyFile(type) {
      if (type == 1) {
        this.$refs.NewTechEngineeHistoryList.open(this.form.id)
      }
      if (type == 2) {
        this.$refs.CommentsListModal.open(this.form)
      }
      if (type == 3) {
        this.$refs.LogList.open(this.form.id)
      }
    },
    chagneHasProjectNo() {
      if (this.form.hasProjectNo != '1') {
        this.$set(this.form, 'projectNo', '')
        this.$set(this.form, 'projectManagerId', '')
        this.$set(this.form, 'projectManager', '')
        this.$set(this.form, 'projectName', '')
      }
    },
  },
}
</script>
<style lang="less" scoped>
@import '~@assets/less/hte-main.less';
.fixed-menu {
  position: fixed;
  right: 20px;
  z-index: 1;
  width: 80px;
  top: 172px;
}

.functionMould {
  background-color: #ffffff;
  padding: 10px;
  text-align: center;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  padding: 10px;
  cursor: pointer;
  &:hover {
    > span,
    > i {
      color: #146595;
    }
  }
}
.functionMould > span {
  width: 100%;
  text-align: center;
  font-size: 12px;
  color: #000000;
  display: block;
}
.menu-icon {
  font-size: 24px;
  color: #31a0e1;
}
/deep/ .ant-form .ant-form-item:not(.self-form-item) .ant-form-item-label {
  width: 120px;
}

.mouldTips {
  border-radius: 5px;
  padding-left: 15px;
  font-size: 14px;
  font-weight: normal;
  color: #085082;
  line-height: 22px;
  display: inline-block;
}

.page-main {
  .container {
    .content {
      margin-top: 20px;

      section {
        .section-table {
          .add-btn {
            margin-left: 0;
            margin-bottom: 10px;
          }
        }
      }
    }
  }

  .tips-box {
    margin-top: 32px;

    .add-btn {
      width: 180px;
      height: 40px;
      line-height: 40px;
      background-color: #4095e4;
      border-radius: 2px;
    }
  }
}

.icon-file {
  background-image: url('../../../assets/file.png');
}

.cr-content-pop {
  p {
    margin-bottom: 15px;
    color: #666;

    &:last-child {
      margin-bottom: 0;
    }
  }
}
</style>
<style lang="less" scoped>
/deep/ #process-container {
  width: unset !important;
}

#process-container {
  background: #fff;
  padding: 40px 22px;
  width: auto;
  margin: 0 auto;
  -webkit-box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.15);
  box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.15);
  justify-content: flex-end;
}
</style>
